package com.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bbs.dto.CategoryAdd;
import com.bbs.mapper.CategoryMapper;
import com.bbs.pojo.Category;
import com.bbs.pojo.Result;
import com.bbs.service.ICategoryService;
import com.bbs.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result<Object> addCategory(CategoryAdd categoryAdd) throws Exception{
        Category category = new Category();
        ObjectUtil.mergeObj(categoryAdd, category);
        category.setCreateTime(LocalDateTime.now());
        return Result.succeed();


    }

    @Override
    public Result<Map<String, List<Category>>> groupByTag() {
        List<Category> categoryList = categoryMapper.selectList(new QueryWrapper<>());
        Map<String, List<Category>> categoryMap = new HashMap<>();
        for(Category category: categoryList){
            if(categoryMap.get(category.getTag()) != null){
                List<Category> list = categoryMap.get(category.getTag());
                list.add(category);
            }else{
                List<Category> list = new ArrayList<>();
                list.add(category);
                categoryMap.put(category.getTag(), list);
            }
        }
        return Result.withData(categoryMap);
    }

    @Override
    public Result<Category> getCategory(String id) {
        Category category = new Category();
        category.setCategoryId(id);
        category = getOne(new QueryWrapper<>(category));
        return Result.withData(category);
    }
}
